program write_tp_2km_grid

  use netcdf
  use mongof_common_mod

  implicit none

  character(30) mongo_uri
  character(30) mongo_db
  character(30) mongo_col
  character(256) grid_file_path
  integer cid, nlon, nlat, nlev
  real(8), allocatable, dimension(:) :: lon, lat, lev

  interface
    integer(c_int) function write_grid(cid, nlon, nlat, lon, lat) result(res) bind(c, name='write_grid')
      use iso_c_binding
      integer(c_int), intent(in), value :: cid
      integer(c_int), intent(in), value :: nlon
      integer(c_int), intent(in), value :: nlat
      real(c_double), intent(in) :: lon(nlon)
      real(c_double), intent(in) :: lat(nlat)
    end function write_grid
  end interface

  call get_command_argument(1, mongo_uri)
  call get_command_argument(2, grid_file_path)

  mongo_uri = 'mongodb://' // trim(mongo_uri) // char(0)
  mongo_db = 'hntp' // char(0)
  mongo_col = 'tp_2km_grids' // char(0)
  call handle_mongo_error(mongoc_connect(mongo_uri, mongo_db, mongo_col, cid), __FILE__, __LINE__)

  call handle_mongo_error(mongoc_create_grid_index(cid), __FILE__, __LINE__)

  call read_grid(grid_file_path, nlon, nlat, nlev, lon, lat, lev)

  call handle_mongo_error(write_grid(cid, nlon, nlat, lon, lat), __FILE__, __LINE__)

  call mongoc_final()

contains

  subroutine read_grid(file_path, nlon, nlat, nlev, lon, lat, lev)

    character(*), intent(in) :: file_path
    integer, intent(inout) :: nlon
    integer, intent(inout) :: nlat
    integer, intent(inout) :: nlev
    real(8), intent(inout), allocatable :: lon(:)
    real(8), intent(inout), allocatable :: lat(:)
    real(8), intent(inout), allocatable :: lev(:)

    integer ierr, ncid
    integer lon_dimid, lat_dimid, lev_dimid
    integer lon_varid, lat_varid, lev_varid

    ierr = NF90_OPEN(file_path, NF90_NETCDF4, ncid)

    ierr = NF90_INQ_DIMID(ncid, 'lon', lon_dimid)

    ierr = NF90_INQ_DIMID(ncid, 'lat', lat_dimid)

    ierr = NF90_INQ_DIMID(ncid, 'lev', lev_dimid)

    ierr = NF90_INQUIRE_DIMENSION(ncid, lon_dimid, len=nlon)

    ierr = NF90_INQUIRE_DIMENSION(ncid, lat_dimid, len=nlat)

    ierr = NF90_INQUIRE_DIMENSION(ncid, lev_dimid, len=nlev)

    allocate(lon(nlon), lat(nlat), lev(nlev))

    ierr = NF90_INQ_VARID(ncid, 'lon', lon_varid)

    ierr = NF90_INQ_VARID(ncid, 'lat', lat_varid)

    ierr = NF90_INQ_VARID(ncid, 'lev', lev_varid)

    ierr = NF90_GET_VAR(ncid, lon_varid, lon)

    ierr = NF90_GET_VAR(ncid, lat_varid, lat)

    ierr = NF90_GET_VAR(ncid, lev_varid, lev)

    ierr = NF90_CLOSE(ncid)

  end subroutine read_grid

end program write_tp_2km_grid
